package com.client.util;

import com.Emplyment.entity.Article;
import com.Emplyment.util.CacheHotCompany;
import com.client.mapper.ArticleMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CompanyCallable implements Callable<String> {


    private RedisTemplate redisTemplate;

    private ArticleMapper articleMapper;

    private Integer companyId;

    private static final String companyHASH_KEY = "company:HASH:data";

    public CompanyCallable(ArticleMapper articleMapper, RedisTemplate redisTemplate,Integer companyId) {
        this.articleMapper = articleMapper;
        this.redisTemplate = redisTemplate;
        this.companyId = companyId;
    }

    /**
     * 来执行从数据库中查询到数据然后添加到缓存当中
     * @return
     * @throws Exception
     */

    @Override
    public String call() throws Exception {
        Article hotEmplyee = articleMapper.getEmplyeeById(companyId);
        CacheHotCompany cacheHotCompany = new CacheHotCompany();
        long expireTime = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(2);
        //如果数据为空那么添加一个空的数据解决缓存穿透问题
        if (hotEmplyee!= null) {
            cacheHotCompany.setCompany(hotEmplyee);
            cacheHotCompany.setExpireAt(expireTime);
            ObjectMapper mapper = new ObjectMapper();
            String emplymentJSON = mapper.writeValueAsString(cacheHotCompany);
            redisTemplate.opsForHash().put(companyHASH_KEY, companyId, emplymentJSON);
            log.info("缓存添加成功:{}",emplymentJSON);
        }
        return null;
    }
}
